<?php
/*
 *  Default blog engine
 *  
 *  (c) Taras Kudla, t@etter.com
 */

class mod_blog {

	private $System=null;

	private $lang = null;
	
	private $ViewDateFormat = "d m, h:i";
	
	private $itemsPerPage = 10;

        private $CutLength = 500;

/*
 * Default blog engine module
 */

	public function __construct(init & $System){
		
		$this->System=&$System;
		
		$this->System->lang->setModuleLanguage("blog",array("en","ru","ua"),"en",$this->lang);
		
		$this->initOptions();
		
	}
	
	private function initOptions(){
	
	$options=$this->System->options->GetAll();
		
	if(isset($options["itemsperpage"])) {	
	$this->itemsPerPage=$options["itemsperpage"];
	}

	if(isset($options["dateformat"])) {	
	$this->ViewDateFormat=$options["dateformat"];
        }

        if(isset($options["cutlength"])) {
	$this->CutLength=$options["cutlength"];
	}
	
	}
	
	public function resetOptions(){
	
	if($this->System->checkPOST("items","date","cutlength")){
	
	if( is_numeric($_POST["items"])){
	
	$this->System->options->Set("blog","itemsperpage",$_POST["items"]);
	
	$this->itemsPerPage = $_POST["items"];
	}
	
	$this->System->options->Set("blog","dateformat",$this->System->escapeString($_POST["date"]));
	
	$this->ViewDateFormat = $_POST["date"];


        $this->System->options->Set("blog","cutlength",$this->System->escapeString($_POST["cutlength"]));

	$this->CutLength = $_POST["cutlength"];

	}
		
	return $this->System->view->GetTemplate("blog","options",array("items"=>$this->itemsPerPage,"date"=>$this->ViewDateFormat,"cutlength"=>$this->CutLength) );
	
	}
	
	
	private function ReadAll(){
		
		
		$perPage=10;
		
		$offset=0;
		
		$q=$this->System->dbo->select("mod_blog","*"," limit ".$this->perPage." offset ".$offset." ");
		
		
	}
	
	private function Cut(&$string,$length=null){

                $length=$this->CutLength;
		
		if(strlen($string)<$length) return $string;
				
		$result="undefined";
		
		$i=$length;while($i<strlen($string)){
			
			if(preg_match("/(\s|\.|;|,)/",$string[$i],$tmp)){
				
				$result=substr($string,0,$i);	
				
				$string=substr($string,$i,strlen($string));	
				
				break;	
			}
			
			$i++;
			}
		
		return $result;		
	}
	

	public function Read(){
	
	if(!isset($_GET["id"]) || !is_numeric($_GET["id"]))
		{
		
		}
	$id=$this->System->escapeString($_GET["id"]);
	
	$q=$this->System->dbo->select("mod_blog","*","where item_id='".$id."' limit 1 offset 0");
	
	if(count($q)==0) {
	
	}
		
	return $this->System->view->GetTemplate("blog","view");	
	}
	
	private function GetTag(){
	
	}
	
	public function ReadTags(){
	
		if(isset($_GET["tag"]) ){
			
			return $this->GetTag();
		}
		
		
	}
	
	public function calendar(){
	
	// options for ajax
	
	$currentYear=date("Y");

	$currentMonth=date("n");

	$lastMonth=($currentMonth==1)?12:($currentMonth-1);
	
	
	return "It works!!!";
	}
	
		
	public function ReadThemes(){
	
	$q=$this->System->dbo->select("mod_blog_sections","*","order by total desc limit 20 offset 0");
	
	return $this->System->view->GetTemplate("blog","readthemes",array("count"=>count($q),"data"=>&$q ) );
	}
	
	/*
	 *  
	 */
	
	private function month($m){
	
		$m=(int)$m;
		
		if($m<1 || $m>12) $m=0; 
		
		$l=$this->lang->get("m".$m);
		
		return $l;					
	}
	
	/*
	 * Main userview function
	 */
	 
	public function view(){
		
		$page=( isset($_GET["page"]) && is_numeric($_GET["page"]))?$this->System->escapeString($_GET["page"]):0;
			
		$section=(isset($_GET["section"]) && is_numeric($_GET["section"]))?$this->System->escapeString($_GET["section"]):null;
		
		$items=$this->System->dbo->select("mod_blog as a, mod_blog_sections as b,users as c",
			"a.title,a.head,a.item_id,a.section,a.author,a.pubdate,b.name,b.section_id,c.firstname,c.lastname,c.id",
			"where b.section_id=a.section and c.id=a.author order by a.item_id desc");
		
		$tags=array();
		$date=array();
		foreach($items as $k=>$v){
			
			$tagsArray=$this->System->dbo->select("mod_blog_taglinks as a,mod_blog_tags as b","b.name",
				"where b.tag_id = a.tag_id and a.item_id='".$v["item_id"]."'",_RESULT_LIST);
			
			$tags["item".$v["item_id"]]=
				$this->System->view->GetTemplate("blog","tagssmall",array("tags"=>$tagsArray,"count"=>count($tagsArray)));
			
			/*
			 * Date reformat
			 */
			
			$date["item".$v["item_id"]]="Unknown date format";
			if(preg_match("/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})\s*([0-9]{1,2})(:|.)([0-9]{1,2}).*$/s",$v["pubdate"],$match)){
									
				$date["item".$v["item_id"]]=
					preg_replace(array("/y/i","/m/i","/d/i","/h/i","/i/i"),array($match[1],$this->month($match[2]),$match[3],$match[4],$match[6]),$this->ViewDateFormat);		
			}
							
		}
		
		$this->System->options->GetAll();
		
		return $this->System->view->GetTemplate("blog","view",array(
			
			"count"=>count($items),
			
			"items"=>&$items,
			
			"tags"=>&$tags,
			
			"date"=>&$date
			));	
			
		
	}
	
	public function art(){
	
	if(!isset($_GET["id"]) || !is_numeric($_GET["id"]) ) return false;
	
	$id=$this->System->escapeString($_GET["id"]);
	
	$Query = $this->System->dbo->select("mod_blog","*","where item_id='$id' limit 1 offset 0",_RESULT_ROW);

	if(count($Query)==0) return false;
	
	$tagsArray=$this->System->dbo->select("mod_blog_taglinks as a,mod_blog_tags as b","b.name",
			"where b.tag_id = a.tag_id and a.item_id='".$id."'",_RESULT_LIST);
			
	$tags=$this->System->view->GetTemplate("blog","tagssmall",array("tags"=>$tagsArray,"count"=>count($tagsArray)));		
	
	$section = $this->System->dbo->select("mod_blog_sections","name","where section_id='".$Query["section"]."' limit 1 offset 0",_RESULT_ROW);
	
	$User=$this->System->dbo->select("users","firstname,lastname","where id='".$Query["author"]."' limit 1 offset 0",_RESULT_ROW);
	
	$section = $section["name"];
	
	$date="Unknown date format";
			if(preg_match("/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})\s*([0-9]{1,2})(:|.)([0-9]{1,2}).*$/s",$Query["pubdate"],$match)){
									
				$date=
					preg_replace(array("/y/i","/m/i","/d/i","/h/i","/i/i"),array($match[1],$this->month($match[2]),$match[3],$match[4],$match[6]),$this->ViewDateFormat);		
			}
	
	
	
	return $this->System->view->GetTemplate("blog","article",array("item"=>&$Query,"date"=>$date,"tags"=>$tags,"section"=>$section,"user"=>$User) );	
	
	}
	
	
	/*
	 * Administartor functions
	 */					
	
	/* 
	 * Article updating
	 */
	private function ArticleUpdate(){
	
	if(isset($_GET["update"]) && is_numeric($_GET["update"])){
		
		$id=$this->System->escapeString($_GET["update"]);


                $exists=$this->System->dbo->select("mod_blog","section","where item_id='".$id."' limit 1 offset 0",_RESULT_ROW);

                if(count($exists)==0){
                    return $this->System->errors->Message($this->lang->get("e2"));
                }

                $oldSection=$exists["section"];

		if($this->System->checkPOST("title","tags","content","section") ){

                list($title,$tags,$section)=$this->System->escapePOST("title","tags","section");

                $content=str_replace("'","&#039;",$_POST["content"]);

                if(empty($content) || strlen($content)==0){
                    print $this->System->errors->Message($this->lang->get("e1"));
                }
                else {

                    /*
                     * Parsing ad updating
                     */
                   			/*
			 *  Tags Processing
 			 */

			$tagsArray=explode(",",$tags);

                        $tagsAdded=array();

			$tagList=$this->System->dbo->select("mod_blog_tags","name",null,_RESULT_LIST);

                        foreach($tagsArray as $k=>$v){

                            $v=trim($v);

                            if( !empty($v) && strlen($v)>0 ){

                            $tagsAdded[]=$v; }
                        }

			foreach($tagsAdded as $k=>$v){

                                $v=trim($v);

				if(!in_array($v,$tagList) && !empty($v) && strlen($v)>0 ){
					$this->System->dbo->insert("mod_blog_tags",array("name"=>$v));
				}
			}
			/*
			 * Parsing <blogcut>
			 */

			if(preg_match("/^(.*)\{blogcut\}(.*)$/si",$content,$tmp)){

				$head=$tmp[1];

				$content=$tmp[2];
			}
			else {

				$head=$this->Cut($content);

			}
                 /*
                  * Article updating
                  */
                $this->System->dbo->update("mod_blog","set title='".$title."',head='".$head."',
                content='".$content."', section='".$section."' where item_id='".$id."'");


                if($oldSection!=$section){

                    $this->System->dbo->update("mod_blog_sections","set total=total-1 where section_id='".$oldSection."' ");

                    $this->System->dbo->update("mod_blog_sections","set total=total+1 where section_id='".$section."' ");

                }


                /*
                 * And, at last, tag links
                 */

                $this->System->dbo->delete("mod_blog_taglinks","where item_id='".$id."'");

                if(count($tagsAdded)>0){

				$tagsIds=$this->System->dbo->select("mod_blog_tags","tag_id"," where name IN ('".implode("','",$tagsAdded)."')");

				foreach( $tagsIds as $k=>$v){

					$this->System->dbo->insert("mod_blog_taglinks", array("tag_id"=>$v["tag_id"],"item_id"=>$id) );
				}
			}
                 

                }


                print $this->System->errors->Message($this->lang->get("b18"));

		}

                $this->System->base->GetTinyMCE("full");

                $this->System->base->SetHTMLHeader("js","blog.js");

		$Query=$this->System->dbo->select("mod_blog","*"," where item_id='".$id."'",_RESULT_ROW);

                $tags=$this->System->dbo->select("mod_blog_tags","name","where tag_id IN (select tag_id from mod_blog_taglinks where item_id='".$id."')",_RESULT_LIST);
		
		return $this->System->view->GetTemplate("blog","update",array("section"=>$this->SectionSelect($Query["section"]),
                    "title"=>$Query["title"],"content"=>$Query["content"],"tags"=>implode(" , ",$tags)) );
	}
	
	
	}
	
	private function ArticleDelete(){
	
	if(isset($_GET["delete"]) && is_numeric($_GET["delete"])){
	
	$Article=$this->System->escapeString($_GET["delete"]);

        $Query=$this->System->dbo->select("mod_blog","section","where item_id='".$Article."' limit 1 offset 0",_RESULT_ROW);

        if(count($Query)==0) return null;

        $section=$Query["section"];

        $this->System->dbo->update("mod_blog_sections","set total=total-1 where section_id='".$section."'");
	
	$this->System->dbo->delete("mod_blog","where item_id='".$Article."'");
	
	$this->System->dbo->delete("mod_blog_taglinks","where item_id='".$Article."'");
	
	return true;
	}
	
	}
	
	public function GetAll(){
		
		/*
		 * select a.title,a.content,a.section,a.author,b.name,b.section_id,c.firstname,c.lastname,c.id 
		from mod_blog as a, mod_blog_sections as b,users as c where b.section_id=a.section and c.id=a.author
		 */
		
		if(isset($_GET["delete"])){
			$this->ArticleDelete();
		}

		if(isset($_GET["update"])){
			return $this->ArticleUpdate();
		}
		
		
		$items=$this->System->dbo->select("mod_blog as a, mod_blog_sections as b,users as c",
			"a.title,a.head,a.item_id,a.section,a.author,a.pubdate,b.name,b.section_id,c.firstname,c.lastname,c.id",
			"where b.section_id=a.section and c.id=a.author order by id ");
		
		/*
		 * Tags, Date
		 */
		
		$tags=array();
		$date=array();
		foreach($items as $k=>$v){
			
			$tagsArray=$this->System->dbo->select("mod_blog_taglinks as a,mod_blog_tags as b","b.name",
				"where b.tag_id = a.tag_id and a.item_id='".$v["item_id"]."'",_RESULT_LIST);
			
			$tags["item".$v["item_id"]]=
				$this->System->view->GetTemplate("blog","tagssmall",array("tags"=>$tagsArray,"count"=>count($tagsArray)));
			
			/*
			 * Date reformat
			 */
			
			$date["item".$v["item_id"]]="Unknown date format";
			if(preg_match("/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})\s*([0-9]{1,2})(:|.)([0-9]{1,2}).*$/s",$v["pubdate"],$match)){
									
				$date["item".$v["item_id"]]=
					preg_replace(array("/y/i","/m/i","/d/i","/h/i","/i/i"),array($match[1],$this->month($match[2]),$match[3],$match[4],$match[6]),$this->ViewDateFormat);		
			}
							
		}
		$this->System->base->SetHTMLHeader("js","blog.js");
		
		if(count($items)==0){
                    return $this->System->errors->Message($this->lang->get("b13"));
                }
		
		return $this->System->view->GetTemplate("blog","getall",array(
			
			"count"=>count($items),
			
			"items"=>&$items,
			
			"tags"=>&$tags,
			
			"date"=>&$date
			));		
	}
	
	public function ajaxtools(){
		
		if(isset($_GET["ResetSection"]) && isset($_GET["Value"]) && !empty($_GET["Value"])
			 && is_numeric($_GET["ResetSection"]) ){
		
			$value=trim($this->System->escapeString($_GET["Value"]));
			
			if(strlen($value)==0)return false;
		
			$this->System->dbo->update("mod_blog_sections","set name='".$value."' where section_id='".$_GET["ResetSection"]."'");
		}
		if(isset($_GET["ResetTag"]) && isset($_GET["Value"]) && !empty($_GET["Value"])
			&& is_numeric($_GET["ResetTag"]) ){
			
			$value=trim($this->System->escapeString($_GET["Value"]));
			
			if(strlen($value)==0)return false;
			
			$this->System->dbo->update("mod_blog_tags","set name='".$value."' where tag_id='".$_GET["ResetTag"]."'");
		}
		
		if(isset($_GET["ItemHead"]) && is_numeric($_GET["ItemHead"])){
			
			$item=$this->System->escapeString($_GET["ItemHead"]);
			
			$q=$this->System->dbo->select("mod_blog","head","where item_id='".$item."' limit 1 offset 0",_RESULT_LIST);
			
			print (isset($q[0])?$q[0]:"not found");
		}		
		
		
		return null;
	}
	
	
	private function SectionSelect($current=null){
	
		$t="<select name='section'>";
	
		$q=$this->System->dbo->select("mod_blog_sections","section_id,name","limit 300 offset 0");
		
		$i=0;
		while($i<count($q)){
			
			$t.="<option value='".$q[$i]["section_id"]."' ".( (int)$q[$i]["section_id"]==$current?"selected":null).">".$q[$i]["name"]."</option>";
			$i++;
		}	
		
		return $t."</select>";
	}
	
	
	public function GetSections(){
					
		if($this->System->checkPOST("name","Submit","add")){
				
				$name=$this->System->escapeString($_POST["name"]);
				
				if(!empty($name)){
					$this->System->dbo->insert("mod_blog_sections",array("name"=>$name));	
				} 
			}			
		
		if(isset($_GET["delete"]) && is_numeric($_GET["delete"])){
			
			$id=$this->System->escapeString($_GET["delete"]);


			$this->System->dbo->delete("mod_blog_sections","where section_id='".$id."'");
			// cleaning links
			$this->System->dbo->delete("mod_blog_taglinks","where item_id in
                            ( select item_id from mod_blog where section='".$id."') ");
                
                        $this->System->dbo->delete("mod_blog","where section='".$id."'");
						
		}
		$this->System->base->SetHTMLHeader("js","blog.js");
		
		$q=$this->System->dbo->select("mod_blog_sections","section_id,name","limit 300 offset 0");
		
		return $this->System->view->GetTemplate("blog","sections",array("data"=>&$q,"count"=>count($q)));
		
	}
	
	private function GetTagsJS(){
	
		$q=$this->System->dbo->select("mod_blog_tags","name",null,_RESULT_LIST);
		
		$js="var TagsArray= new Array(\"".implode("\",\"",$q)."\");";
		
		return $js;		
	}
	
	
	public function GetTags(){
					
		if($this->System->checkPOST("name","Submit","add")){
				
				$name=$this->System->escapeString($_POST["name"]);
				
				if(!empty($name)){
					$this->System->dbo->insert("mod_blog_tags",array("name"=>$name,"rank"=>0));	
				} 
			}
			
		if(isset($_GET["delete"]) && is_numeric($_GET["delete"])){
			
			$id=$this->System->escapeString($_GET["delete"]);
			
			$this->System->dbo->delete("mod_blog_tags","where tag_id='".$id."'");
			// cleaning links
			$this->System->dbo->delete("mod_blog_taglinks","where tag_id='".$id."'");
			
		}
		$this->System->base->SetHTMLHeader("js","blog.js");
		
		$q=$this->System->dbo->select("mod_blog_tags","tag_id,rank,name","limit 300 offset 0");
		
		return $this->System->view->GetTemplate("blog","tags",array("data"=>&$q,"count"=>count($q)));		
	}
		
	public function Write(){
		
		if($this->System->checkPOST("title","content","tags","section")){
			
			list($title,$tags,$section)=$this->System->escapePOST("title","tags","section");
			
			$content=str_replace("'","&#039;",$_POST["content"]);

                        if(empty($content) || strlen($content)==0){

                           print $this->System->errors->Message($this->lang->get("e1") );
                        }

                        else {
			
			if($this->System->dbo->select("mod_blog",
					"item_id","where title='".$title."' and section='".$section."' limit 1 offset 0",_RESULT_BOOL)) {
			
				/*
				 *  Message that exists
				 */
			
				return false;					
			}
			
			/*
			 *  Tags Processing
 			 */
			
			$tagsArray=explode(",",$tags);

                        $tagsAdded=array();
			
			$tagList=$this->System->dbo->select("mod_blog_tags","name",null,_RESULT_LIST);

                        foreach($tagsArray as $k=>$v){

                            $v=trim($v);

                            if( !empty($v) && strlen($v)>0 ){

                            $tagsAdded[]=$v; }
                        }

			foreach($tagsAdded as $k=>$v){

                                $v=trim($v);

				if(!in_array($v,$tagList) && !empty($v) && strlen($v)>0 ){
					$this->System->dbo->insert("mod_blog_tags",array("name"=>$v));
				}				
			}
			/*
			 * Parsing <blogcut>
			 */
			
			if(preg_match("/^(.*)\{blogcut\}(.*)$/si",$content,$tmp)){
				
				$head=$tmp[1];
				
				$content=$tmp[2];
			}
			else {
			
				$head=$this->Cut($content);
			
			}
			
			/*
			 * Inserting an article
			 */
			
			$this->System->dbo->insert("mod_blog",array(
					"title"=>$title,
					
					"head"=>$head,
					
					"content"=>preg_replace("/'/","&#039;",$content),
					
					"section"=>$section,
					
					"author"=>$this->System->user->GetUserID(),

                                        "votes"=>0,

                                        "rating"=>0,
					
					"pubdate"=>date("Y-m-d H:i:s")									
					) );
			/*
			 * Updating section
			 */			
			$this->System->dbo->update("mod_blog_sections","set total=total+1 where section_id='".$section."'");
			/*
			 * Getting item_id
			 */
			$itemId=$this->System->dbo->select("mod_blog","item_id","where title='".$title."' and section='".$section."' limit 1 offset 0",_RESULT_LIST);
						
			$itemId=$itemId[0];			
			/*
			 * Set tags links
			 */
			if(count($tagsAdded)>0){
			
				$tagsIds=$this->System->dbo->select("mod_blog_tags","tag_id"," where name IN ('".implode("','",$tagsAdded)."')");
				
				foreach( $tagsIds as $k=>$v){

					$this->System->dbo->insert("mod_blog_taglinks", array("tag_id"=>$v["tag_id"],"item_id"=>$itemId) );	
				}		
			}						
			
			//$this->System->base->sendHeader("blog-getall","message=success");

                        }
		}
		
		
						
			$this->System->base->GetTinyMCE("full");
			
			$this->System->base->SetHTMLHeader("js","blog.js");
			
			return $this->System->view->GetTemplate("blog","write",array("section"=>$this->SectionSelect(),"TagsJS"=>$this->GetTagsJS()));
				
	}
	
	public function install(){
		
		// Setting default options
		$this->System->options->Set("blog","itemsperpage","10");
		
		$this->System->options->Set("blog","dateformat","d m, h:i");

                $this->System->options->Set("blog","cutlength","500");		
		
		$table["name"]="mod_blog";
		$table["field"][]=array("name"=>"item_id","type"=>"int_auto");
		$table["field"][]=array("name"=>"title","type"=>"char");
		$table["field"][]=array("name"=>"section","type"=>"int");
		$table["field"][]=array("name"=>"votes","type"=>"int");
		$table["field"][]=array("name"=>"head","type"=>"text");
		$table["field"][]=array("name"=>"content","type"=>"text");
		$table["field"][]=array("name"=>"author","type"=>"int");
		$table["field"][]=array("name"=>"pubdate","type"=>"datetime");
		$table["field"][]=array("name"=>"rating","type"=>"int");
		$table["ukey"][]=array("field"=>"item_id");		
		$table["key"][]=array("field"=>"section");
		
		$this->System->dbo->createtable($table);
		/* 
		 * Tags Table
		 */ 
		unset($table);
		$table["name"]="mod_blog_tags";
		$table["field"][]=array("name"=>"tag_id","type"=>"int_auto");
		$table["field"][]=array("name"=>"name","type"=>"char");
		$table["field"][]=array("name"=>"rank","type"=>"int","default"=>"0");
		$table["pkey"][]=array("field"=>"tag_id");
		$table["key"][]=array("field"=>"name");
		
		$this->System->dbo->createtable($table);
		unset($table);
		/* 
		 * Sections table
		 */ 
		$table["name"]="mod_blog_sections";
		$table["field"][]=array("name"=>"section_id","type"=>"int_auto");
		$table["field"][]=array("name"=>"name","type"=>"char");
		$table["field"][]=array("name"=>"total","type"=>"int","default"=>0);
		$table["pkey"][]=array("field"=>"section_id");
		$table["key"][]=array("field"=>"name");
		$this->System->dbo->createtable($table);
		unset($table);
		/*
		 * Tag - Article links table
		 */
		$table["name"]="mod_blog_taglinks";
		$table["field"][]=array("name"=>"tag_id","type"=>"int");
		$table["field"][]=array("name"=>"item_id","type"=>"int");
		$table["key"][]=array("field"=>"tag_id");
		$table["key"][]=array("field"=>"item_id");
		$this->System->dbo->createtable($table);
		unset($table);
		
		$this->System->dbo->insert("mod_blog_sections",array("name"=>"Undefined") );
		
		return true;		
	}
	
	public function uninstall(){
		
		// Deleting an options
		
		$this->System->options->Delete("blog");
		
		$this->System->dbo->direct("drop table if exists mod_blog");
		$this->System->dbo->direct("drop table if exists mod_blog_tags");
		$this->System->dbo->direct("drop table if exists mod_blog_sections");
		$this->System->dbo->direct("drop table if exists mod_blog_taglinks");
		
		return true;
	}
}
?>
